<?php declare(strict_types=1);

namespace App\Common;

use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Consul\Agent;
use Swoft\Consul\Health;

/**
 * Class ServiceHelper
 * @Bean()
 */
class ServiceHelper{

    /**
     * @Inject()
     *
     * @var Agent
     */
    private $agent;

    /**
     * @Inject()
     *
     * @var Health
     */
    private $health;

    /**
     * @param string $serviceName
     * @return array
     * 根据服务名 获取健康服务列表
     */
    public function getService(string $serviceName) : array {
        $service = $this->agent->services()->getResult();
        $checks = $this->health->checks($serviceName, ["filter" => "Status==passing"])->getResult();

        $passingNode = [];  // [0=>'s1', 1=>'s2', 2=>'s3']
        foreach ($checks as $check){
            $passingNode[] = $check['ServiceID'];
        }

        if(count($passingNode) == 0) return [];
        return array_intersect_key($service, array_flip($passingNode));
    }

}